angular.module('sale.services', [])
/**
 * 销售数据
 */
.factory('SalesService',function(){ //$rootScope

  //保存从数据库读取的数据
  var getSaleOrdersSub = function(scope){
    return scope.subscribe('sale_orders');
  };

  return {
    /**
     * 总销售额
     */
    analytic : function(scope,field,callback){
      scope.helpers({
        sale_orders: function() {
          return SaleOrders.find();
        }
      });

      scope.autorun(function() {
        if(getSaleOrdersSub(scope).ready() && scope.sale_orders){
          var anaSale={
            totalSale:0,        // 销售额
            orderCount:0,       // 销售单数
            productCount:0,     // 销售台数
            totalMargin:0,      // 毛利
            totalMarginRatio:0, //毛利率
            loaded:false
          };

          if(scope.sale_orders.length){
            scope.sale_orders.forEach(function(order){
              anaSale.totalSale+=order.amount;
              anaSale.orderCount++;
              anaSale.productCount+=order.total_count;
              order.list.forEach(function(product){
                anaSale.totalMargin+=(product.final_price - product.cost_price_default) *product.count;
              });
            });
          }
          anaSale.totalMarginRatio=((anaSale.totalMargin / anaSale.totalSale)*100).toFixed(2);
          anaSale.loaded = true;
          callback(anaSale);
        }
      });
    },

    /**
     * 图表数据
     */
    setChartData : function(scope,field,type,callback){
      // reactive(this).attach(scope);
      if(!scope.sale_orders){
        scope.helpers({
          sale_orders: function() {
            return SaleOrders.find();
          }
        });
      }
      var chartData={},
          labels=[],
          data=[];
          scope.type = type;
      scope.autorun(function() {
        if(getSaleOrdersSub(scope).ready() && scope.sale_orders){
          if(scope.sale_orders.length){
            scope.sale_orders.forEach(function(order){
              order.list.forEach(function(product){
                var arrayIndex = '';
                if('store' == type){
                   arrayIndex = order[type].name;
                }else if('seller' == type){
                   arrayIndex = order[type].employeeName;
                }else{
                  arrayIndex = product.properties[type].value;
                }
                if(!chartData[arrayIndex]){
                  chartData[arrayIndex]=0;
                }
                chartData[arrayIndex]+=product.final_price * product.count;
              });
            });
          }

          var forIndex = 0;
          for(var oLabel in chartData){
            if(forIndex>4){
              break;
            }
            labels.push(oLabel);
            data.push(chartData[oLabel]);
            forIndex++;
          }
          callback(labels,data);
        }
      });
    },

    /**
     * 详细列表，按品牌、单品、门店、销售员统计销售数量、销售额、销售毛利
     */
     list : function(scope,field,property,callback){
      if(!scope.sale_orders){
        scope.helpers({
          sale_orders: function() {
            return SaleOrders.find();
          }
        });
      }
      var listData=[];
      var tempData=[];
      scope.autorun(function() {
        if(getSaleOrdersSub(scope).ready() && scope.sale_orders){

          //建立以property 为key的obj数组
          scope.sale_orders.forEach(function(order){
            order.list.forEach(function(product){
             var arrayIndex = '';
              if('store' == property){
                 arrayIndex = order[property].name;
              }else if('seller' == property){
                 arrayIndex = order[property].name;
              }else{
                arrayIndex = product.properties[property].value;
              }
              if(!tempData[arrayIndex]){ 
                var item = {'name':'','count':0,'sales':0,'margin':0};
                item.name = arrayIndex;
                item.count += product.count;
                item.sales += product.final_price;
                item.margin += product.final_price-product.cost_price_default;
                tempData[arrayIndex] = item;
              }else{
                tempData[arrayIndex].count+=product.count;
                tempData[arrayIndex].sales+=product.final_price;
                tempData[arrayIndex].margin+=product.final_price-product.cost_price_default;
              }
            });
          });
          // console.log(tempData);

          for(var item in tempData){
            listData.push(tempData[item]);
          }

          callback(listData);
        }
      });
    },

    /**
     * 品牌销售详情统计
     */
    brandSaleDetail : function(scope,field,brandName,callback){
      if(!scope.sale_orders){
        scope.helpers({
          sale_orders: function() {
            return SaleOrders.find();
          }
        });
      }
      var brandData=[];
      var tempData=[];

      scope.autorun(function() {
        if(getSaleOrdersSub(scope).ready() && scope.sale_orders){
          //遍历订单，提取品牌销售
          scope.sale_orders.forEach(function(order){
            order.list.forEach(function(product){
              if(brandName==product.properties.brand.value){
                if(!tempData[product.properties.model.value]){
                  tempData[product.properties.model.value] = {'type':product.properties.model.value,'count':0,'sales':0,'margin':0};
                }
                tempData[product.properties.model.value].count+=product.count;
                tempData[product.properties.model.value].sales+=product.final_price;
                tempData[product.properties.model.value].margin+=product.final_price-product.cost_price_default;

              }
            });
          });

          for(var item in tempData){
            brandData.push(tempData[item]);
          }
          callback(brandData);
        }
      });
    }
  };
});
